// 带签名的上传文件代码示例

package uni_oss

import (
	"autoclave/utils/tools"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"net/url"
	"strconv"
	"time"
)

type ResponseCommon struct {
	Code    int
	Message string
	Data    interface{}
}

type ResponseSuccess struct {
	Code    int
	Message string
	Data    map[string]string
}

type SignParams struct {
	Timestamp string `json:"timestamp" form:"timestamp" binding:"required"`
	AppKey    string `json:"app_key" form:"app_key"  binding:"required"`
	NonceStr  string `json:"nonce_str" form:"nonce_str"  binding:"required,min=16,max=16"`
}

// ObjectExistTest 文件是否存在, 带签名
func ObjectExistTest(key string) (exist bool, err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	param := url.Values{}
	param.Add("file_path", key)

	sp := SignParams{
		Timestamp: strconv.FormatInt(time.Now().Unix(), 10),
		AppKey:    "jk_iasux0dkltmtjovm",
		NonceStr:  tools.GetRandomString(16),
	}
	param.Add("timestamp", sp.Timestamp)
	param.Add("app_key", sp.AppKey)
	param.Add("nonce_str", sp.NonceStr)

	sign, err := tools.SignFromMapString(map[string]string{
		"timestamp": sp.Timestamp,
		"app_key":   sp.AppKey,
		"nonce_str": sp.NonceStr,
	}, "")
	if err != nil {
		return
	}
	res, err := tools.HttpPostForm(apiExist, param, map[string]string{
		"Content-Type":  "application/x-www-form-urlencoded",
		"Authorization": sign,
	})
	if err != nil {
		return
	}
	fmt.Println("RES = ", res)
	resp := ResponseCommon{}
	err = json.Unmarshal([]byte(res), &resp)
	if err != nil {
		return
	}
	exist = resp.Code == 0
	return
}

// ObjectPutTest 文件上传, 带签名
func ObjectPutTest(filePath, destObj string) (respSuccess ResponseSuccess, err error) {
	param := url.Values{}
	sp := SignParams{
		Timestamp: strconv.FormatInt(time.Now().Unix(), 10),
		AppKey:    "jk_iasux0dkltmtjovm",
		NonceStr:  tools.GetRandomString(16),
	}
	param.Add("timestamp", sp.Timestamp)
	param.Add("app_key", sp.AppKey)
	param.Add("nonce_str", sp.NonceStr)
	param.Add("dst_path", destObj)
	sign, err := tools.SignFromMapString(map[string]string{
		"timestamp": sp.Timestamp,
		"app_key":   sp.AppKey,
		"nonce_str": sp.NonceStr,
	}, "")
	if err != nil {
		return
	}
	res, err := tools.HttpPostMultipart(apiUpload, filePath, param, map[string]string{
		"Authorization": sign,
	})
	if err != nil {
		return
	}
	fmt.Println("RES = ", res)
	resp := ResponseCommon{}
	err = json.Unmarshal([]byte(res), &resp)
	if err != nil {
		return
	}
	if resp.Code == 0 {
		respSuccess = ResponseSuccess{}
		err = json.Unmarshal([]byte(res), &respSuccess)
		if err != nil {
			return
		}
	}
	// 处理响应
	return
}
func run() {
	rand.Seed(time.Now().UnixNano())
	res, err := ObjectPutTest("src/a.html", "tmp/fuck/97.php")
	//exist, err := ObjectExist("tmp/fuck/97.php")
	fmt.Println("res", res.Data["full_url"])
	fmt.Println("err", err)
}
